import got from 'got';
import {getAlbumInfo, getAlbumTracks, getTrackInfo} from 'd-fi-core';
import type {albumType, trackType} from 'd-fi-core/dist/types';

const instance = got.extend({
  prefixUrl: 'https://api.deezer.com/',
  retry: {
    limit: 4,
    calculateDelay: ({attemptCount}) => attemptCount * 1500,
  },
  hooks: {
    afterResponse: [
      (response) => {
        // @ts-ignore
        const shouldRetry = response.body.includes('Quota limit exceeded') && response.body.includes('4');
        if (shouldRetry) {
          response.statusCode = 429;
        }

        return response;
      },
    ],
  },
});

export const isrc2deezer = async (name: string, isrc?: string) => {
  if (!isrc) {
    throw new Error('ISRC code not found for ' + name);
  }

  const body: any = await instance('track/isrc:' + isrc).json();
  if (body.error) {
    throw new Error(`No match on deezer for ${name} (ISRC: ${isrc})`);
  }

  return await getTrackInfo(body.id);
};

export const upc2deezer = async (name: string, upc?: string): Promise<[albumType, trackType[]]> => {
  if (!upc) {
    throw new Error('UPC code not found for ' + name);
  } else if (upc.length > 12) {
    upc = upc.slice(-12);
  }

  const body: any = await instance('album/upc:' + upc).json();
  if (body.error) {
    throw new Error(`No match on deezer for ${name} (UPC: ${upc})`);
  }

  const albumInfo = await getAlbumInfo(body.id);
  const {data} = await getAlbumTracks(body.id);
  return [albumInfo, data];
};
